﻿using System;

namespace DataFeedService
{
    class DataSourceListener : IDisposable
    {
        private class DataSourceObserver : IObserver<TickUpdate>, IDisposable
        {
            private IDisposable unsubscriber; 
            private Action<TickUpdate> onNext;

            public DataSourceObserver(IDataSource observable, Action<TickUpdate> action)
            {
                onNext = action;
                unsubscriber = observable.Subscribe(this);
            }

            public void OnCompleted()
            {
                //TODO
            }

            public void OnError(Exception error)
            {
                //TODO
            }

            public void OnNext(TickUpdate value)
            {
                onNext(value);
            }

            public void Dispose()
            {
                unsubscriber.Dispose();
            }
        }

        private DataSourceObserver observer;

        public DataSourceListener(IDataSource observable, Action<TickUpdate> action)
        {
            if (observable == null)
            {
                throw new ArgumentException("IDataSource non può essere null.", "observable");
            }

            if (action == null)
            {
                throw new ArgumentException("Expression<Action<TickUpdate>> non può essere null.", "action");
            }

            observer = new DataSourceObserver(observable, action);
        }

        #region IDisposable
        public void Dispose()
        {
            observer.Dispose();
        } 
        #endregion
    }
}
